package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.bean.GCHead;
import com.example.administrator.yanfoxconn.bean.IGMessage;
import com.example.administrator.yanfoxconn.bean.KMDMT;
import com.example.administrator.yanfoxconn.bean.KNZWGreen;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 總務-綠化管理作業模式
 * @Author song
 * @Date 11/24/21 7:55 PM
 */
public class KNGreenProjectActivity extends BaseActivity implements View.OnClickListener{

    private final int MESSAGE_GREEN_PROJECT = 111;//請求成功
    private KNGreenProjectActivity mContext = this;
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTittle;//標題

    @BindView(R.id.lv_list)
    MyListView myListView;
    private MyAdapter adapter;
    private List<KNZWGreen> knArea;
    private String result="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_km_dmt_list);
        ButterKnife.bind(this);
        tvTittle.setText("作業模式");
        btnBack.setOnClickListener(this);
        result = getIntent().getStringExtra("result");
    }
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_title_left:
                    finish();
                    break;
            }
    }

    /**
     * 位置信息及綠化面積
     * @param result
     */
    private void getGreenProject(String result) {
        showDialog();
        String url = Constants.HTTP_GREEN_PROJECT + "?gId="+result ;
        new Thread() {
            @Override
            public void run() {
                String result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        knArea = new ArrayList<KNZWGreen>();
                        for (JsonElement type : array) {
                            KNZWGreen humi = gson.fromJson(type, KNZWGreen.class);
                            knArea.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_GREEN_PROJECT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_TOAST;
                    message.obj = "網絡問題請求失敗,請重試!";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }
    private String ids;//获取ID用于上传
    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_GREEN_PROJECT:
                    myListView.setVisibility(View.VISIBLE);
                    adapter = new MyAdapter(mContext, knArea);
                    myListView.setAdapter(adapter);

                    setListViewHeightBasedOnChildren(myListView);
                    break;
                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(mContext, msg.obj.toString());
                    break;
                case Constants.MESSAGE_UP://t提交提示
                    ToastUtils.showLong(mContext, msg.obj.toString());
                    finish();
                    break;
                case Constants.MESSAGE_NOT_NET://t提交提示
                    ToastUtils.showLong(mContext, R.string.net_mistake);
                    break;
            }
            super.handleMessage(msg);
        }
    };


    public class MyAdapter extends BaseAdapter{
        public Context mContext;
        private List<KNZWGreen> lists;

        public MyAdapter(Context context, List<KNZWGreen> knLists) {
            this.mContext = context;
            this.lists = knLists;
        }
        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(KNGreenProjectActivity.this,R.layout.adapter_button,null);
            Button btn=(Button)view.findViewById(R.id.btn);
            btn.setText(lists.get(position).getProject());
            if (lists.get(position).getFlag().equals("N")){

                btn.setClickable(false);
                btn.setBackgroundColor(getResources().getColor(R.color.color_858585));
            }else{
                btn.setClickable(true);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext,KNGreenUpProjectActivity.class);
                        intent.putExtra("project",lists.get(position).getProject());
                        intent.putExtra("gName",getIntent().getStringExtra("gName"));
                        intent.putExtra("gId",result);
                        startActivity(intent);
                    }
                });
            }

            return view;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        getGreenProject(result);
    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        MyAdapter listAdapter = (MyAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}
